package coolapk.cj.cj.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpGlobalConfig;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import coolapk.cj.cj.config.CqhttpConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zss
 * @created 2021-12-31 19:36
 * @description 获取qq群信息的工具类
 */
@Slf4j
public class CqhttpUtil {

    /**
     * 获取实时的qq群员
     * @return
     */
    public static Map<String, Object> getGroupMembers() {
        Map bodyMap = new HashMap();
        bodyMap.put("group_id", CqhttpConfig.groupId);
        String resultBody = HttpRequest.post(CqhttpConfig.url + "/get_group_member_list?access_token=" + CqhttpConfig.accessToken).
                timeout(HttpGlobalConfig.getTimeout()).
                body(JSONUtil.toJsonStr(bodyMap)).execute().body();
        JSONObject resultJson = JSONUtil.parseObj(resultBody);
        return toCache(resultJson);
    }

    /**
     * 通过qq号获取群成员信息
     * @param qq
     * @return
     */
    public static JSONObject getMemberInfoByQq(String qq) throws Exception {
        Map bodyMap = new HashMap();
        bodyMap.put("group_id", CqhttpConfig.groupId);
        bodyMap.put("user_id", qq);
        bodyMap.put("no_cache", true);
        String resultBody = HttpRequest.post(CqhttpConfig.url + "/get_group_member_info?access_token=" + CqhttpConfig.accessToken).
                timeout(HttpGlobalConfig.getTimeout()).
                body(JSONUtil.toJsonStr(bodyMap)).execute().body();
        JSONObject resultJson = JSONUtil.parseObj(resultBody);
        if (Integer.valueOf(resultJson.get("retcode").toString()) == 0) {
            log.info("获取群成员信息 --> {}", qq);
            return (JSONObject) resultJson.get("data");
        } else {
            log.error("获取成员[ {} ]信息出错", qq);
            throw new Exception("获取成员[ " + qq + " ]信息出错");
        }
    }

    private static Map<String, Object> toCache(JSONObject resultJson) {
        if (Integer.valueOf(resultJson.get("retcode").toString()) == 0) {
            JSONArray data = (JSONArray) resultJson.get("data");
            if (CollUtil.isNotEmpty(data)) {
                log.info("获取群成员列表 --> {} 条", data.size());
                return data.stream().collect(Collectors.toMap(item -> {
                    String value = null;
                    try {
                        value = SpelExpressionUtils.getValue("#root.user_id", item, String.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return value;
                }, item -> item ));
            } else {
                throw new IllegalArgumentException("群成员信息为空，无法验证身份！");
            }
        } else {
            throw new IllegalArgumentException("获取群成员失败，无法验证身份！");
        }
    }
}
